<?php
/**
 * Author:Arthur
 * Date:2013-2-20
 * File Name:receiveDetails.php
 * Email:kingarthurx@sina.cn
 */
session_start();
/* 取得当前project所在的根目录 */
define('ROOT_PATH', str_replace('api/receiveValidation.php', '', str_replace('\\', '/', __FILE__)));
require(ROOT_PATH . 'config/config.php');
/* 载入MYSQL,初始化 */
require(ROOT_PATH . 'include/class/mysql_class.php');
$mysql=new MYSQL($db_host,$db_user, $db_pass, $db_name);
$GLOBALS['mysql']=$mysql;
require (ROOT_PATH . 'include/class/receiveValidation_class.php');
/*八优API*/
require(ROOT_PATH . 'include/class/BayouSmsSender.php');
/*短信发送*/
require(ROOT_PATH . 'include/class/message_class.php');
/*短信发送*/
require(ROOT_PATH . 'include/class/reply_history_class.php');

$method = $_REQUEST['method'];
if (empty($method)) {
		$method = 'info';
	}
if($method == 'info'){
	info();
}
if($method == 'sendsms'){
	$valid=userValidation();
	if($valid == 'ok'){
		$info = sendsms();
		if(!empty($info)){
			print_r($info);
		}
	}else{
		echo $valid;
	}
}
if($method == 'getReply'){
	$valid=userValidation();
	if($valid == 'ok'){
		$text = getReply();
		if(!empty($text)){
			print_r($text);
		}
	}else{
		echo $valid;
	}
}

/**
  * 获取信息,为属性设置值
  */
function getField(){
		$receiveValidation = new receiveValidation();
		$receiveValidation->user_login_name=$_REQUEST['username'];
		$receiveValidation->user_login_password=$_REQUEST['password'];
		$receiveValidation->mobile=$_REQUEST['mobiles'];
		$receiveValidation->msgcount = $_REQUEST['msgcount'];
		$receiveValidation->encodetype = $_REQUEST['encodetype'];
		/**
	 	 * 把短信内容进行两次URL编码转换
	 	 */
		$receiveValidation->content=urlEncode(urlEncode(mb_convert_encoding($_REQUEST['message'], 'gb2312' ,'utf-8')));
	return $receiveValidation;
}

/**
 * 验证用户名密码是否存在
 */
function userValidation(){
	$receiveValidation = getField();
	$arr = $receiveValidation ->findUser();
	if(!empty($arr->user_login_name)){
		$arrx = $receiveValidation ->findUserPassword();
		if(empty($arrx)){
			return "密码不正确!";
		}else{
			$receiveValidation->company_id = $arrx->company_id;
			$apiArr = $receiveValidation ->findUserApi();
			for($i = 0; $i < count($apiArr); $i++){
				if(empty($apiArr[$i]->userapi_id)){
					return "API不存在，请申请API!";
				}else{
					$_SESSION['usercustomer']=$arrx;
					$_SESSION['api']=$apiArr;
				}
			}
		}
	}else{
		return  "用户名不存在!";
	}
	return "ok";
}
	
/**
 * 发送短信
 */
function sendsms(){
	/**
	 * 设置属性
	 */
	$smstype = $_REQUEST['smstype'];
	if(empty($smstype)){
		$smstype =0;
	}
	$timerflag = $_REQUEST['timerflag'];
	if(empty($timerflag)){
		$timerflag=0;
	}
	$timervalue = $_REQUEST['timervalue'];
	$timertype = $_REQUEST['timertype'];
	if(empty($timertype)){
		$timertype=0;
	}
	$timerid = $_REQUEST['timerid'];
	if(empty($timerid)){
		$timerid=0;
	}
	$extno = $_REQUEST['extno'];
	$start_time=date(TIME_FORMAT);
	$success_list="";//成功列表
	$fail_list="";//失败列表
	$success_count=0;//成功发送次数
	$fail_count=0;//失败发送次数
	$receiveValidation = getField();
	//先拿到号码
	$mobileArr = explode(",",$receiveValidation->mobile);
	/**
	 * 200发一次短信,并且去掉重复号码
	 */
	 for($i=0;$i<count(array_unique($mobileArr));$i++){
	 	//短信按照200一截进行批量发送.
	 		if(trim($mobileArr[$i])!=""){
		 		if($i%200==0){
		 			if(count($mobileArr)>1){
		 				$mobile_list=$mobileArr[$i].",";
						continue ;
					}else{
						$mobile_list=$mobileArr[$i];
					}
		 		}else if($i%200!=199&&$i<count($mobileArr)-1){
		 			$mobile_list.=$mobileArr[$i].",";
		 			continue ;
		 		}else{
		 			$mobile_list.=$mobileArr[$i];
		 		}
	 		}else{
	 			continue ;
	 		}
	/**
	 *	获取短信长度，扣除相应的短信条数 
	 */
	$count = countCharacters($receiveValidation->content);
	if($count == "5"){
		$reText = "短讯长度最多是5条内容！";
	}else{
		/**
		 * 短信发送成功后，给对象中设置值，扣除相应的短信条数
		 */
		$receiveValidation->company_id=$_SESSION['usercustomer']->company_id;
		/*短信發送數*/
		$receiveValidation->balance=count(array_unique($mobileArr)) * $count;
		$arr = $receiveValidation->findInfo();
		/*判断短信发送条数*/
		if($receiveValidation->balance > $arr->balance){
			$balance = "对不起，余额不够发送短信,只能够发送".$arr->balance."条短信!";
		}else{
			
			//根据获取的短信内容和联系人列表,发送短信
			if($receiveValidation->content==""||trim($receiveValidation->content)==""){
				$txts ="短信內容不能為空!";
			}else{
				//根据短信内容计算花费的credit.
				$message->cost=countCharacters($receiveValidation->content);
				if (preg_match('/[\x80-\xff]./', $receiveValidation->content)) {
				/**
			 	 * 把短信内容进行两次URL编码转换
			 	 */
			 	$receiveValidation->content = urlEncode(urlEncode(mb_convert_encoding($receiveValidation->content, 'gb2312' ,'utf-8')));
				//$unicode=1;
				}else{
				//是英文的话再把空格转换下.
				$receiveValidation->content = str_replace(' ', '%20',$receiveValidation->content);
				$receiveValidation->content = @ereg_replace(Chr(10), '%0A',$receiveValidation->content);
				$receiveValidation->content = @ereg_replace(Chr(13), '',$receiveValidation->content);
				}
			}
			$url = "http://sms.c8686.com/Api/BayouSmsApiEx.aspx";
			$params="func=sendsms&username=".$_SESSION['api'][0]->api_username."&password=".$_SESSION['api'][0]->api_password."&mobiles=".$mobile_list."&message=".$receiveValidation->content."&smstype=$smstype&timerflag=$timerflag&timervalue=$timervalue&timertype=$timertype&timerid=$timerid&extno=$extno";
			$method="POST";
			$my_header="";
			/**
			 * 实例化 八优api 调用use_curl函数 发送短信
			 */
			$BayouSmsSender = new BayouSmsSender();
			$content =$BayouSmsSender->use_curl($url, $params, $method, $my_header);//返回的内容是一个数组
			/**
		 	 * 数组内的内容格式，是xml，需要解析，解析后，放入list
		 	 */
		 	//执行完成后需要做判断
		 	//判断返回结果里是否包含回车,换行.
		 	//然后再根据回车换行进行数组分割.
		 	//最后判断每个号码的发送情况.从而生成success list和fail list.
		 	//$result_list=explode(Chr(10),$content['body']);
		 	$xml_string = $content['body'];
			$xml = simplexml_load_string($xml_string);
			//对象转换成数组，方便引用
			$result_list = (array)$xml;
		 	//判断返回的内容errorcode 是否成功
		 	if($result_list['errorcode']==0){
		 		//发送成功		
					if($success_count==0){
						$success_list=$mobile_list;
					}else{
						$success_list.=",".$mobile_list;
					}
					$credit = $receiveValidation->updateInfo($arr->balance);
					$mobileArr = explode(",",$success_list);
					$success_count++;
					$alert="发送成功";
			}else{
				//发送失败		
					if($fail_count==0){
						$fail_list=$mobile_list;
					}else{
						$fail_list.=",".$mobile_list;
					}
					$mobileArr = explode(",",$fail_list);
					$fail_count++;
					$alert="发送失败";
			}
	  	}
	}
  }
	  	/**
		 * 记录每条短信的发送状态,如果短信数量支持发送，才记录到数据库当中
		 */
	 	if($receiveValidation->balance <= $arr->balance){
	 		$message = new Message();
			for($k = 0; $k<count($mobileArr); $k++){
				$message->api_id=$_SESSION['api'][0]->api_id;
				$message->sms_record_time=date(TIME_FORMAT);
				$message->sms_success_list=$mobileArr[$k];
				$message->sms_fail_list=$fail_list;
				$message->sms_success_count=$success_count;
				$message->sms_fail_count=$fail_count;
				$message->sms_content=mb_convert_encoding(URLDecode(URLDecode($receiveValidation->content)),'utf-8','gb2312');
				$message->user_id=$_SESSION['usercustomer']->user_id;
				$message->company_id=$_SESSION['usercustomer']->company_id;
				$message->department_id=$_SESSION['usercustomer']->department_id;
				$end_time=date(TIME_FORMAT);
				$message->sms_record_remark.=" start at ".$start_time."; end at ".$end_time;
				$message->sendMessage();
			}
	 	}
		
		/*查询余额*/
		$balances = $receiveValidation->findInfo();
		/*設置返回信息*/
		if(empty($reText)){
			$reText=0;
		}
		$txt = $balance;
		if(empty($balance)){
				$txt = $alert.",".$txts;
		}
		if($alert == "发送成功"){
			$succeed=0; //0 为发送成功
		}else{
			$succeed=1; //1为发送失败
		}
		/**
		 * 返回信息
		 * balance : 剩余短信数
		 * sendFlashCount ：发送短讯数量
		 * sendTime ： 发送时间
		 * flashContent ： 发送内容
		 * mobiles ： 发送号码
		 * errordescription ： 错误内容描述
		 * reText ： 发送短讯最长长度
		 * succeed ： 短信发送成功是否状态
		 */
		$text["body"]='[{"balance":"'.$balances->balance.'"},{"sendFlashCount":"'.$receiveValidation->balance.'"},{"sendTime":"'.date(TIME_FORMAT).'"},{"flashContent":"'.mb_convert_encoding(URLDecode(URLDecode($receiveValidation->content)),'utf-8','gb2312').'"},{"mobiles":"'.$receiveValidation->mobile.'"},{"errordescription":"'.$txt.'"},{"reText":"'.$reText.'"},{"succeed":"'.$succeed.'"}]';
		return array('body'=>$text["body"]);
		
}	
	
	
/**
 * 计算消息内容数量
 */
function countCharacters($text) {
	$length = mb_strlen($text);
	$credit = 1;
	if (preg_match('/[\x80-\xff]./', $text)) {
		//中文计算短信条数的方法
		if ($length <= 66) {
			$credit = 1;
		} else
			if ($length > 66 && $length <= 132) {
				$credit = 2;
			} else
				if ($length > 132 && $length <= 198) {
					$credit = 3;
				} else
					if ($length > 198&& $length <= 264) {
						$credit = 4;
					} else
						if ($length > 264) {
							$credit = 5;//最长335
						}
	} else {
		//英文计算短信条数的方法
		if ($length <= 132) {
			$credit = 1;
		} else
			if ($length > 132 && $length <= 264) {
				$credit = 2;
			} else
				if ($length > 264 && $length <= 396) {
					$credit = 3;
				} else
					if ($length > 396 && $length <= 528) {
						$credit = 4;
					} else
						if ($length > 528) {
							$credit = 5;
						}
	}

	return $credit;
}

/**
 * 编码转换
 */
function getUnicode($word){
	$word0 = iconv('gbk', 'utf-8', $word);
    $word1 = iconv('utf-8', 'gbk', $word0);
    $word =  ($word1 == $word) ? $word0 : $word;
	 // 拆分汉字
    preg_match_all('#(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+)#s', $word, $array, PREG_PATTERN_ORDER);
    foreach ($array[0] as $cc)
    {
		if(preg_match('/[\x80-\xff]./', $cc)){
			$arr = str_split($cc); 
			$bin_str = '';
			foreach ($arr as $value)
			{
				$bin_str .= decbin(ord($value));
			}
			
			$bin_str = preg_replace('/^.{4}(.{4}).{2}(.{6}).{2}(.{6})$/','$1$2$3', $bin_str);
			$return[] =  dechex(bindec($bin_str));
			//echo $cc."是中文"."<br />";
		}else{
			//$return[] =bindec($cc);
			$arr = str_split($cc); 
			$bin_str = '';
			foreach ($arr as $value)
			{
				$bin_str .= decbin(ord($value));
			}
			$str=dechex(bindec($bin_str));
			if(strlen($str)<4){
				for($i=strlen($str);$i<4;$i++){
					$str="0".$str;
				}
			}
			$return[] = $str;
			//echo $cc."不是中文"."<br />";
		}
    }
    return implode('', $return);
}
/*提示不可缺少的参数*/
function info(){
	echo "请在url上加上method=sendsms,才能发送短信！";
}

/**
 * 获取回复短信内容
 */
function getReply(){
	$receiveValidation = getField();
	$receiveValidation->company_id = $_SESSION['usercustomer']->company_id;
	$count = getServerReply($receiveValidation->msgcount,$receiveValidation->encodetype);
	if($count == '1'){
		$smsarr = $receiveValidation->getReply();
	}else if($count == '2'){
		$tString = "未有新回复的短讯！";
	}
	
	$txt="";
	for($i = 0; $i < count($smsarr); $i++){
		if(count($smsarr) - $i == 1){
			$string = "";
		}else{
			$string = ",";
		}
		/**
		 * mobile:电话号码
		 * destmobile：回复到号码(发短信出去的号码)
		 * content:短讯内容
		 * time：回复时间
		 */
		$txt.='[{"mobile":"'.$smsarr[$i]->mobile.'"},{"destmobile":"'.$smsarr[$i]->destmobile.'"},{"content":"'.$smsarr[$i]->content.'"},{"time":"'.$smsarr[$i]->time.'"}]'.$string;
	}
	/*返回提示*/
	if(empty($txt)){
		$reply['ret']=$tString;
	}else{
		$reply['ret']=$txt;
	}
	return array('body'=>$reply["ret"]);
}

/**
 * 获取八优服务器内回复的内容
 */
function getServerReply($msgcount,$encodetype){
	$reply = new Reply();
	$replyArr = $reply->getUserApi($_SESSION['usercustomer']->company_id);
	if(!empty($replyArr->api_username)){
		//获取回复短信URL
		$url="http://sms.c8686.com/Api/BayouSmsApiEx.aspx?func=getreply&username=".$replyArr->api_username."&password=".$replyArr->api_password."&msgcount=$msgcount&encodetype=$encodetype";
		$ch = curl_init();  
		curl_setopt($ch,CURLOPT_URL,$url);  
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);     
	   	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); 
	 	$content= curl_exec($ch);  
		curl_close($ch);
	}else{
		$str = "请申请API或检查您的账号密码是否正确.";
		return $str;
	}
	//解析平常的xml文件
	//$xml = simplexml_load_string($xml_string);
	//解析带有cdata 的xml 文件
	$xml = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
	if(count($xml->reply->msg) > 0){
	for($i = 0; $i < count($xml->reply->msg); $i++){
			$reply->company_id = $_SESSION['usercustomer']->company_id;
			$reply->clientid = $replyArr->api_username;
			$reply->mobile = trim($xml->reply->msg[$i]->mobile);
			$reply->destmobile = $xml->reply->msg[$i]->destmobile;
			$reply->content = $xml->reply->msg[$i]->content;
			$reply->time = $xml->reply->msg[$i]->time;
			$reply->msg_type = 2;
			/**
			 * 获取的回复内容插入到本地数据库
			 */
			$reply ->insertReply();
	}
	return "1"; //如果返回为1，说明有获取到新的回复短讯
  }else{
  	return "2"; //如果返回为2，说明回复的短讯已经获取
  }
}

